from flask import Flask, request, jsonify, send_from_directory
from flask_socketio import SocketIO, emit
import os
import subprocess
import signal
import json

app = Flask(__name__)
socketio = SocketIO(app)

# 存储主站服务器的进程ID
main_server_process = None

with open('hidden/adminpwd.txt', 'r') as f:
    ADMIN_PASSWORD = f.read().strip()

def verify_password(password):
    return password == ADMIN_PASSWORD

@app.route('/')
def serve_admin():
    return send_from_directory(os.path.dirname(__file__), 'admin.html')

@app.route('/start-server', methods=['POST'])
def start_server():
    global main_server_process
    password = request.json.get('password')
    if not verify_password(password):
        return jsonify({'message': '密码错误'}), 403
    if main_server_process is None:
        main_server_process = subprocess.Popen(['python', 'server.py'], cwd=os.path.dirname(__file__))
        socketio.emit('status', '运行中')
        return jsonify({'message': '主站服务器已启动'})
    else:
        return jsonify({'message': '主站服务器已经在运行中'})

@app.route('/stop-server', methods=['POST'])
def stop_server():
    global main_server_process
    password = request.json.get('password')
    if not verify_password(password):
        return jsonify({'message': '密码错误'}), 403
    if main_server_process is not None:
        main_server_process.terminate()
        main_server_process = None
        socketio.emit('status', '已停止')
        return jsonify({'message': '主站服务器已停止'})
    else:
        return jsonify({'message': '主站服务器未在运行中'})

@app.route('/upload-files', methods=['POST'])
def upload_files():
    password = request.form.get('password')
    if not verify_password(password):
        return jsonify({'message': '密码错误'}), 403
    if 'file' not in request.files:
        return jsonify({'message': '没有文件上传'}), 400

    files = request.files.getlist('file')
    for file in files:
        filename = file.filename
        filepath = os.path.join(os.path.dirname(__file__), filename)
        file.save(filepath)

    return jsonify({'message': '文件上传并更新成功'})

@app.route('/server-status', methods=['GET'])
def server_status():
    global main_server_process
    if main_server_process is None:
        return jsonify({'status': '已停止'})
    else:
        return jsonify({'status': '运行中'})

@app.route('/save-motto', methods=['POST'])
def save_motto():
    password = request.json.get('password')
    if not verify_password(password):
        return jsonify({'message': '密码错误'}), 403
    data = request.json
    motto = data.get('motto')
    if not motto:
        return jsonify({'error': 'No motto provided'}), 400

    mottos_file_path = os.path.join(os.path.dirname(__file__), 'mottos.json')
    with open(mottos_file_path, 'r', encoding='utf-8') as f:
        mottos = json.load(f)

    new_id = max(motto['id'] for motto in mottos) + 1 if mottos else 1
    new_motto = {
        "id": new_id,
        "content": motto
    }
    mottos.append(new_motto)

    with open(mottos_file_path, 'w', encoding='utf-8') as f:
        json.dump(mottos, f, ensure_ascii=False, indent=4)

    return jsonify({'message': 'Motto saved successfully'})

@socketio.on('connect')
def handle_connect():
    if main_server_process is None:
        emit('status', '已停止')
    else:
        emit('status', '运行中')

@app.route('/background.png')
def bg_return():
    return send_from_directory(os.path.dirname(__file__), 'background.png')

if __name__ == '__main__':
    socketio.run(app, host='0.0.0.0', port=2311)